<template>
  <div>
  <!--工具类-->
  <Row>
    <i-col span="24" class-name="y_query_right" v-has=tRole.COUPONS_1_101>
      <Button type="primary" icon="md-add"  class="y_condition"
              @click="add">新增优惠券模板
      </Button>
    </i-col>
  </Row>
  <hr>
    <Row >
      <i-col span="24" class-name="y_query_right" >
        <Select placeholder="模板类型" class="y_condition" style="min-width: 100px; text-align: left;" v-model="param.couponType" :clearable=true >
          <Option v-for="item in couponTypeDict" :value="item.value" :key="item.value">{{ item.name }}</Option>
        </Select>
        <Button type="primary" icon="md-search" class="y_condition" @click="searchList">过滤查询</Button>
      </i-col>
    </Row>

    <Row>
      <div class="tip_div"  v-show="couponList.length === 0">
        <strong>操作提示 :  </strong>
        <br><br>
        <p>1. 我们只支持优惠券这一种优惠方式，任何的优惠都是通过发放优惠券实现的</p>
        <p>2. 我们支持两种优惠券：按比例折扣（满200打7折） 和 按金额折扣（满200减30）</p>
        <p>3. 无门槛优惠券由于没有使用门槛，一定要慎用</p>
        <p>4. 目前的会员体系中，会每个月为会员发放三张优惠券（需人工发放）</p>
      </div>
    </Row>


    <!--      <Row>
      <Table stripe border :context="this" :columns="tableTitles" :data="couponList" class="base_table" style="width: 100%;"
             no-data-text="暂无数据" ></Table>
    </Row>-->
      <List border class="data-list">
        <template v-if="couponList.length == 0">
          <ListItem class="list-item">
            <div style="width: 100%; text-align: center; color: #ccc;">暂无数据</div>
          </ListItem>
        </template>
        <template v-else>
          <ListItem v-for="(item, index) in couponList" :key="index" class="list-item">
            <div class="item-top">
              <KeyValueView title="标题" :value="item.title"></KeyValueView>
              <Tag :color="getValidityColor(item)">{{getValidity(item)}}</Tag>
            </div>
            <div class="item-content">
              <KeyValueView title="类型" :value="getType(item)"></KeyValueView>
              <KeyValueView title="启用状态" :value="getState(item.state)"></KeyValueView>
              <KeyValueView title="发放方式" :value="getDistributionMethod(item)"></KeyValueView>
              <KeyValueView title="折扣" :value="getDiscount(item)"></KeyValueView>
            </div>
            <div class="item-bottom">
              <Button type="primary" size="small" icon="md-create" v-has="tRole.COUPONS_1_201" @click="editCouponModel(item.id)">编辑</Button>
              <Button type="info" size="small" icon="md-flash" v-has="tRole.COUPONS_1_202" @click="showCouponModelAction(item.id, item.state, item.title)">{{item.state==0?'禁用':'启用'}}</Button>
              <Button type="error" size="small" icon="md-trash" v-has="tRole.COUPONS_1_203" @click="deleteCouponModel(item.id, item.title)">删除</Button>
            </div>
          </ListItem>
        </template>
      </List>
      <div style="margin-top: 20px; text-align: right;">
        <Page :total="page.total" :page-size="page.stepNumber" :current="page.currentPage" @on-change="changePage"
              @on-page-size-change="sizeChange" :page-size-opts="[40,60,80,120]"
              show-sizer show-elevator/>
      </div>
    <Modal
      v-model="modalModify.isShow"
      :title="modalModify.title"
      :mask-closable="false"
      :loading="modalModify.isLoading"
      @on-ok="webAddEditCouponModel"
      :footer-hide="modalModify.isOnlyShow"
      :styles="{bottom:'20px',width:'70%'}">

      <Form ref="paramCouponModel" :model="param.couponModel" :rules="rules.baseRules" ::label-width=120
           >
        <div class="modal_base_div" >

          <Row >
            <Alert type="warning" >VIP月度优惠券需选择"当月有效"，"唯一性校验"栏应选择"有效期内唯一"！</Alert>
          </Row>

          <Row style="">
            <i-col span="20">
              <FormItem label="模板类型 :" prop="type" :label-width=120 >
                <RadioGroup v-model="param.couponModel.type" >
                  <Radio v-for="item in couponTypeDict" :disabled="param.couponModel.id || param.couponModel.state === 0" :label="item.value">
                    <span>{{ item.name }}</span>
                    <span style="color: #8d8d8d;font-size: 0.8rem">{{item.value==100?'(例如:满$100减$10)':'(例如:满$100减免8%)'}}</span>
                  </Radio>
                </RadioGroup>
              </FormItem>
            </i-col>
          </Row>

          <Row style="">
              <FormItem label="优惠券标题:" prop="title" :label-width=120>
                <Input v-model.trim="param.couponModel.title"  placeholder="内部展示，可中文" :disabled="param.couponModel.state === 0"></Input>
              </FormItem>
          </Row>

          <Row style="">
            <FormItem label="有效期计算方式 :" prop="validityPeriodType" :label-width=120>
              <RadioGroup v-model="param.couponModel.validityPeriodType" >
                <Radio :label="1" :disabled="param.couponModel.state === 0">按天数计算</Radio>
                <Radio :label="2" :disabled="param.couponModel.state === 0">当月有效</Radio>
              </RadioGroup>
            </FormItem>

          </Row>
          <Row style="" v-if="param.couponModel.validityPeriodType == 1">
            <i-col span="12">
              <FormItem label="开始时间 :"  :label-width=100 >
                <Row>
                  <i-col span="22">
                    <DatePicker type="datetime" format="yyyy-MM-dd HH:mm" v-model="param.couponModel.effectiveTimeStr"
                                placement="bottom-end" placeholder="选择日期" class="modal_newuser_form_input"
                                style="width: 90%" :disabled="param.couponModel.state === 0"></DatePicker>
                  </i-col>
                  <i-col span="2">
                    <Tooltip content="不选择开始时间时，优惠券为领取/发放时即时生效。" max-width="160"><Button icon="md-help"></Button></Tooltip>
                  </i-col>
                </Row>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="有效期(天) :" prop="validityPeriod" :label-width=120 >
                <InputNumber v-model.trim="param.couponModel.validityPeriod" :min="1"
                       style="width: 60%" :disabled="param.couponModel.state === 0"></InputNumber>
              </FormItem>
            </i-col>
          </Row>
          <Row style="">
            <i-col span="8"  >
              <FormItem label="使用条件 : 满" prop="threshold" :label-width=120 >
                <InputNumber v-model.trim="param.couponModel.threshold" :min="0"
                             :formatter="value => `$ ${value}`"
                             :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                             style="width: 100%" :disabled="param.couponModel.state === 0"></InputNumber>
              </FormItem>
            </i-col>
              <i-col span="6"  v-show="param.couponModel.type==100">
                <FormItem label="减 " prop="faceValue" :label-width=60 >
                  <InputNumber v-model.trim="param.couponModel.faceValue" :min="1"
                               :formatter="value => `$ ${value}`"
                               :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                               style="width: 100%" :disabled="param.couponModel.state === 0"></InputNumber>
                </FormItem>
              </i-col>

            <i-col span="6" v-show="param.couponModel.type==200">
              <FormItem label="减 :" prop="discountRate" :label-width=60 >
                <InputNumber v-model.trim="param.couponModel.discountRate" :max="100" :step="1" :min="1"
                             :formatter="value => `${value}%`"
                             :parser="value => value.replace('%', '') "style="width: 100%" :disabled="param.couponModel.state === 0"></InputNumber>
              </FormItem>
            </i-col>

          </Row>

          <Row>
            <FormItem label="发放方式 :" prop="distributionMethod" :label-width=120 >
              <RadioGroup v-model="param.couponModel.distributionMethod">
                <Radio v-for="item in couponDistriubtionMethodDict" :label="item.value" :disabled="param.couponModel.state === 0">
                  <span>{{ item.name }}</span>
                </Radio>
              </RadioGroup>
            </FormItem>
          </Row>

          <Row style="">
            <FormItem label="兑换规则:" prop="uniqueType" :label-width=120>
              <RadioGroup v-model="param.couponModel.uniqueType" >
                <Radio :label="1" :disabled="param.couponModel.state === 0 || param.couponModel.distributionMethod == 100 || param.couponModel.validityPeriodType == 2">无限制，每个账号均可多次重复兑换</Radio>
                <Radio :label="2" :disabled="param.couponModel.state === 0 || param.couponModel.validityPeriodType == 2">每个账号此生只能兑换一次</Radio>
                <Radio :label="3" :disabled="param.couponModel.state === 0">每个账号同一时间只能拥有一张，之前兑换的该券过期后方可再次兑换</Radio>
              </RadioGroup>
            </FormItem>
          </Row>

          <div  style="text-align: center " v-show="param.couponModel.distributionMethod==100">
            <div class="modal_base_div_title"><strong>优惠券码 :</strong></div>
            <div class="base_key" style="text-align: left;width: 100%">用户可在PC和App中通过以下券码来兑换该优惠券。不同的券码是否能重复兑换取决于兑换规则。不同券码的提供主要是为了对应不同的推广渠道</div>
          <Row style="margin-top: 1rem">
              <i-col span="12" v-for="(item, index) in param.couponModel.couponCode" >
                <FormItem :key="index">
                  <strong>( 序号{{index+1}} )</strong>&nbsp;&nbsp;券码 :&nbsp;&nbsp;
                  <Input v-model.trim="param.couponModel.couponCode[index]" class="modal_newuser_form_input" ></Input>
                  <Button  @click="removeCodeItem(index)">删除</Button>
                </FormItem>
              </i-col>
          </Row>
            <Row>
              <div style="text-align: center">
                <Button type="info" ghost @click="couponCodeAdd" icon="md-add" >新增券码
                </Button>
              </div>
            </Row>
          </div>

          <div  v-show="param.couponModel.distributionMethod==200">
            <div class="modal_base_div_title"><strong>发放角色 :</strong></div>
          <Row style="">
            <i-col span="20" style="max-height:250px;overflow-x:auto ">
              <FormItem  :label-width=120 >
                <Tree :data="roleList" show-checkbox :multiple="true" ref="Tree" :disabled="param.couponModel.state === 0"></Tree>
              </FormItem>
            </i-col>
          </Row>
          </div>
        </div>
      </Form>
    </Modal>
    <Modal
      v-model="modalAction.isShow"
      :title="modalAction.title"
      :loading="modalAction.isLoading"
      @on-ok="actionChangeState(modalAction.id,modalAction.type,modalAction.name)"
      :mask-closable="false">
      {{modalAction.content}}
    </Modal>
  </div>
</template>

<script>
  import ICol from "../../../node_modules/view-design/src/components/grid/col";
  import tiyData from "./js/couponModel/coupon_model_data";
  import {init, add, modify,commonData,webAddOrModify, webList,changeState, deleteCouponDefine} from "./js/couponModel/coupon_model_fun"
  import KeyValueView from "../widgets/KeyValueView";

  export default {
    components: {KeyValueView, ICol},
      data(){
        return {
            //列表
            couponList:tiyData.tData.couponModelList,
            tableTitles:tiyData.tTable(this),
            page:tiyData.tPage,
            param:tiyData.tParam,
            //新增和编辑
            modalModify:tiyData.tStatus.modalModify,
            modalAction:tiyData.tStatus.modalAction,
            // couponModel:tiyData.tParam.couponModel,
            rules:tiyData.tStatus.rules,
            roleList:tiyData.tData.roleTreeData,
            tRole:{
                COUPONS_1_101 : "COUPONS-1-101",
                COUPONS_1_201 : "COUPONS-1-201",
                COUPONS_1_202 : "COUPONS-1-202",
                COUPONS_1_203 : "COUPONS-1-203",
            }
        }
      },
      computed : {

          stateDict(){
            return this.$store.getters.dictionaries.stateDict
          },
          couponTypeDict(){
              return this.$store.getters.dictionaries.couponType
          },
          couponDistriubtionMethodDict(){
              return this.$store.getters.dictionaries.couponDistriubtionMethod
          },
      },
      methods: {

        searchList(){
            tiyData.tPage.currentPage = 1;
            webList(this,tiyData);
        },
        changePage(page){
            tiyData.tPage.currentPage = page;
            webList(this, tiyData);
        },
        sizeChange(p){
            tiyData.tPage.stepNumber = p;
            webList(this, tiyData);
        },
        add(){
            this.$refs["paramCouponModel"].disabled = false;
            tiyData.tStatus.modalModify.isOnlyShow = false;
            add(this,tiyData);
        },
        webAddEditCouponModel(){
          this.$refs["paramCouponModel"].disabled = false;
          webAddOrModify(this,tiyData);
        },
        editCouponModel(id){
            tiyData.tStatus.modalModify.isOnlyShow = false;
            modify(this,tiyData,id);
        },
        showCouponModelInfo(id){
            tiyData.tStatus.modalModify.isOnlyShow = true;
            this.$refs["paramCouponModel"].disabled = true;
            modify(this,tiyData,id);
        },
        couponCodeAdd(){
            tiyData.tParam.couponModel.couponCode.push("");
        },
        removeCodeItem(index){
            tiyData.tParam.couponModel.couponCode.splice(index,1);
        },
        showCouponModelAction(id,state, title){
          this.modalAction.isShow = true;
          this.modalAction.isLoading = true;
          this.modalAction.type = state;
          this.modalAction.id = id;
          this.modalAction.name = title;
          this.modalAction.content = "确定"+(state==0?'停用':'启用')+"模板？";
        },
        actionChangeState(id,state,title){
          changeState(this,tiyData,id,state==0?1:0,title);
        },
        deleteCouponModel(id, title){
          this.$Modal.confirm({
            title: "确认",
            content: "确认删除优惠券模版"+title+"？删除后无法找回！",
            onOk: () => {
                deleteCouponDefine(this, tiyData, id, title);
            }
          });
        },
        getType(item) {
          return item.type===200?"折扣券":"现金抵扣券";
        },
        getState(item) {
          return item.state===0?"生效中":"已禁用";
        },
        getDistributionMethod(item) {
          return item.distributionMethod===100?'用户兑换':'后台发放';
        },
        getDiscount(item) {
          let discountValue = "";
          let couponType = item.type;
          if(couponType===100){
            discountValue = '$'+item.faceValue;
          }else if(couponType == 200){
            discountValue = (100-item.discountRate*100).toFixed(1)+"%";
          }
          return '满 $'+item.threshold+' 减 '+ discountValue;
        },
        getValidityColor(item) {
          switch(item.validityPeriodType){
            case 1:
              if(item.effectiveTime){ //有生效时间
                let now = new Date().getTime();
                if(item.effectiveTime > now){ //还没到生效时间
                  return "#5cadff";
                }
                let endTimeStamp = item.validityPeriod+item.effectiveTime;
                if (endTimeStamp < now){//已过期
                  return "#757575";
                }

                return "#19be6b";//生效中
              } else { //即时起效
                return "default";
              }
            case 2:
              return "default";
            default:
              return "default";
          }
        },
        getValidity(item) {
          let self = this;
          switch(item.validityPeriodType){
            case 1:
              if(item.effectiveTime){ //有生效时间
                let days = 0;
                let now = new Date().getTime();
                if(item.effectiveTime > now){ //还没到生效时间
                  days = (item.validityPeriod/24/3600/1000).toFixed(0);
                  return(
                    self.$tiyBJTime(item.effectiveTime)+'生效,有效期'+days+'天'
                  );
                }
                let endTimeStamp = item.validityPeriod+item.effectiveTime;
                if (endTimeStamp < now){
                  return '已过期';
                }

                let endTime = self.$tiyBJTime(endTimeStamp);
                days = ((endTimeStamp-now)/24/3600/1000).toFixed(0);
                return(
                  endTime+'失效,仅剩'+days+'天'
                );
              } else { //即时起效
                let days = (item.validityPeriod /24/3600/1000).toFixed(0);
                return ('获取后'+days+'天内有效');
              }
            case 2:
              return ('当月有效');
            default:
              return ("");
          }
        },
      },
      created() {
        init(this,tiyData);
        commonData(this,tiyData);
        // webList(this,tiyData);
      }
  }
</script>

<style lang="less" scoped>
@import  (once,optional) "../css/base";
  .modal_newuser_form_input {
    width: 180px;
    margin-right: 10px;

  }
  .modal_base_div {
    text-align: left;
    margin-top: 20px;
    padding: 20px;
    /*border: dotted thin #d1d1d1*/
  }

  .modal_base_div_title {
    text-align: left;
    margin-bottom: 10px
  }

.data-list {
  margin: 1rem 0rem;
  line-height: 25px;
  .list-item {
    .flex-colum-wrap;
    justify-items: left;
    align-items: start;
    .item-checkbox {
      display: inline-block;
      width: 25px;
      height: 25px;
      text-align: center;
      vertical-align: top;
    }
    .item-img {
      width: 130px;
      text-align: center;
      display: inline-block;
    }
    .item-top{
      width: 100%;
      margin-bottom: 5px;
      .flex-row-wrap;
      justify-content: space-between;
    }
    .item-content {
      margin-bottom: 35px;
      text-align: left;
    }
    .item-bottom{
      //position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      display: block;
      //padding: 0 1rem 0.5rem 0;
      text-align: right;
      button {
        margin-left: 0.5rem;
      }
    }
  }
}
</style>
